package org.zhaya.sdk.processors.condition;

import cn.hutool.core.util.StrUtil;
import io.logz.sawmill.Condition;
import io.logz.sawmill.Doc;
import io.logz.sawmill.annotations.ConditionProvider;
import io.logz.sawmill.parser.ConditionParser;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;

/**
 * @author wangpei
 * @version 5.7.0
 * @date 2022-10-18
 */
@ConditionProvider(type = "in", factory = InCondition.Factory.class)
public class InCondition implements Condition {

    /**
     * 解析key名
     */
    private final String path;
    /**
     * in集合，逗号分割
     */
    private final String value;

    public InCondition(String path, String value) {
        this.path = Objects.requireNonNull(path);
        this.value = Objects.requireNonNull(value);
    }

    @Override
    public boolean evaluate(Doc doc) {
        boolean flag = doc.hasField(path);
        if (flag) {
            Object pathValue = doc.getField(path);
            if (Objects.isNull(pathValue)) {
                return false;
            }
            Set<String> inCollection = new HashSet<>(StrUtil.split(value, StrUtil.COMMA));
            if (pathValue instanceof List) {
                List<Object> valuesList = (List<Object>) pathValue;
                return valuesList.stream().allMatch(o -> inCollection.contains(o.toString()));
            } else {
                return inCollection.stream().anyMatch(o -> o.equals(pathValue.toString()));
            }
        }
        return false;
    }

    public static class Factory implements Condition.Factory {

        @Override
        public Condition create(Map<String, Object> config, ConditionParser conditionParser) {
            Configuration configuration = JsonUtils.fromJsonMap(Configuration.class, config);
            return new InCondition(configuration.getField(), configuration.getInCollection());
        }
    }

    @Data
    @NoArgsConstructor
    public static class Configuration {
        private String field;
        private String inCollection;
    }
}
